<!--
 * @Author: your name
 * @Date: 2020-10-15 19:15:53
 * @LastEditTime: 2020-10-15 19:57:15
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /03-Ajax/06-xhr封装post请求.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="js/jquery-1.12.4.js"></script>
</head>

<body>
    <script>


        function post(url, data, success) {
            const xhr = new XMLHttpRequest();

            if (Object.prototype.toString.call(url).slice(8, -1) === 'Object') {
                const option = url;
                url = option.url;
                data = option.data;
                success = option.success;
            }

            if (!!data) {
                const type = Object.prototype.toString.call(data).slice(8, -1);
                switch (type) {
                    case 'Function':
                        success = data;
                        data = undefined;
                        break;
                    case 'Object':
                        data = JSON.stringify(data).replace(/:/g, "=").replace(/"/g, '').replace(/,/g, '&').match(/\{([^)]*)\}/)[1];
                        break;
                }
            }

            xhr.open('post', url);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
            xhr.send(data || null);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status == 200) {
                    success.call(xhr);
                }
            }
        }

        post('http://127.0.0.1:8000/delay', function () {
            console.log(this.response);
        })
        post({
            url: 'http://127.0.0.1:8000/delay',
            data: '',
            success: function () {
                console.log(this.response);
            }
        })

        post('https://autumnfish.cn/api/user/check', 'username=99887766', function () {
            console.log(this.response);
        })
        post({
            url: 'https://autumnfish.cn/api/user/check',
            data: 'username=99887766',
            success: function () {
                console.log(this.response);
            }
        })

        post('http://www.tuling123.com/openapi/api', { key: '932f61cbc52b46a4bccc6e166a210c5b', info: '晚上有空嘛' }, function () {
            console.log(this.response);
        })
        post({
            url: 'http://www.tuling123.com/openapi/api',
            data: { key: '932f61cbc52b46a4bccc6e166a210c5b', info: '晚上有空嘛' },
            success: function () {
                console.log(this.response);
            }
        })
    </script>
</body>

</html>